package io.gitee.chearnee.fw.sidecar.util;

import jakarta.servlet.http.HttpServletRequest;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.net.InetAddress;

/**
 * @author cn
 * @version 1.0
 * @description
 * @date 12/26/2022 3:04 PM
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class IPUtils {
    private static final String UNKNOWN = "unknown";

    public static String getRequestIPAddress() {
        RequestAttributes requestAttributes = null;
        try {
            requestAttributes = RequestContextHolder.currentRequestAttributes();
        } catch (Exception ignored) {

        }
        if (!(requestAttributes instanceof ServletRequestAttributes servletRequestAttributes)) {
            return "";
        }
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String ip = null;
        String ipAddresses = request.getHeader("X-Forwarded-For");
        if (ipAddresses == null || ipAddresses.isEmpty() || UNKNOWN.equalsIgnoreCase(ipAddresses)) {
            ipAddresses = request.getHeader("Proxy-Client-IP");
        }

        if (ipAddresses == null || ipAddresses.isEmpty() || UNKNOWN.equalsIgnoreCase(ipAddresses)) {
            ipAddresses = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ipAddresses == null || ipAddresses.isEmpty() || UNKNOWN.equalsIgnoreCase(ipAddresses)) {
            ipAddresses = request.getHeader("HTTP_CLIENT_IP");
        }

        if (ipAddresses == null || ipAddresses.isEmpty() || UNKNOWN.equalsIgnoreCase(ipAddresses)) {
            ipAddresses = request.getHeader("X-Real-IP");
        }

        if (ipAddresses != null && !ipAddresses.isEmpty()) {
            ip = ipAddresses.split(",")[0];
        }

        if (ip == null || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ipAddresses)) {
            ip = request.getRemoteAddr();
        }

        return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
    }

    @SneakyThrows
    public static String getCurrentIpAddress() {
        return InetAddress.getLocalHost().getHostAddress();
    }
}
